import os
import re
import string

def sanitize_filename(name):
    """Remove invalid Windows filename characters"""
    sanitized = ''.join(c for c in name if c not in “？?”)
    return sanitized.strip()

# Read chapter names from 1.txt
with open('1.txt', 'r', encoding='utf-8') as f:
    content = f.read()

# Extract chapter names using regex
pattern = r'<a href="[^"]+">(第\d+话[^<]+)</a>'
chapters = re.findall(pattern, content)

# Path to the folder containing the numbered directories
folder_path = r'D:/EdgeDownload/协议换爱'

# Rename each folder
for i, chapter in enumerate(chapters, 1):
    old_name = os.path.join(folder_path, f"{i:03d}")
    
    # Skip if folder doesn't exist or is already renamed
    if not os.path.exists(old_name) or not re.match(r'^\d{3}$', os.path.basename(old_name)):
        print(f"Skipping {i:03d} - folder already renamed or doesn't exist")
        continue
        
    sanitized_chapter = sanitize_filename(chapter)
    new_name = os.path.join(folder_path, f"{i:03d}-{sanitized_chapter}")
    
    try:
        os.rename(old_name, new_name)
        print(f"Renamed {i:03d} to {chapter}")
    except FileNotFoundError:
        print(f"Folder {i:03d} not found, skipping")
    except Exception as e:
        print(f"Error renaming {i:03d}: {str(e)}")

print("Folder renaming complete")
